package org.linlinjava.litemall.admin.web;

import com.github.pagehelper.PageInfo;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.admin.annotation.LoginAdmin;
import org.linlinjava.litemall.admin.dao.GoodsAllinone;
import org.linlinjava.litemall.admin.util.CatVo;
import org.linlinjava.litemall.admin.util.LitemallProductVo;
import org.linlinjava.litemall.core.systemConfig.SystemConfig;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/admin/goods")
public class AdminGoodsController {
    private final Log logger = LogFactory.getLog(AdminGoodsController.class);

    @Autowired
    private PlatformTransactionManager txManager;

    @Autowired
    private LitemallGoodsService goodsService;
    @Autowired
    private LitemallGoodsSpecificationService specificationService;
    @Autowired
    private LitemallGoodsAttributeService attributeService;
    @Autowired
    private LitemallProductService productService;
    @Autowired
    private LitemallCategoryService categoryService;
    @Autowired
    private LitemallBrandService brandService;
    @Autowired
    private LitemallNewBrandService newBrandService;

    @GetMapping("/list")
    public Object list(@LoginAdmin Integer adminId,
                       String goodsSn, String name, Integer cId,
                       @RequestParam(value = "page", defaultValue = "1") Integer page,
                       @RequestParam(value = "limit", defaultValue = "10") Integer limit,
                       String sort, String order, Integer flag){
        if(adminId == null){
            return ResponseUtil.unlogin();
        }
        List<Integer> newGoodsIds=null;

        /*
        * falg为1代表查询库存不足。2代表库存积压
        * */
        if(flag==1){
            List<LitemallProduct> product = productService.queryByNum();
            List<LitemallProduct> products = operateNum(product);
            Set<Integer> goodIds = products.stream().filter(m->m.getNumber()<=m.getSmallNumber()).map(LitemallProduct::getGoodsId).collect(Collectors.toSet());
	        newGoodsIds=goodIds.size()>0?new ArrayList<>(goodIds):null;
        }else if(flag==2){
            List<LitemallProduct> product = productService.queryByNum();
            List<LitemallProduct> bigNumIsNotNull = product.stream().filter(m->m.getBigNumber()!=null).collect(Collectors.toList());
            Set<Integer> highGoodsIds = bigNumIsNotNull.stream().filter(s->s.getNumber()>=s.getBigNumber()).map(LitemallProduct::getGoodsId).collect(Collectors.toSet());
	        newGoodsIds = highGoodsIds.size()>0?new ArrayList<>(highGoodsIds):null;

        }
	    if(newGoodsIds==null && flag!=0){
            return ResponseUtil.fail(403,"暂无数据");
	    }
        List<LitemallGoods> goodsList = goodsService.querySelective(goodsSn, name, cId, page, limit, sort, order,newGoodsIds);
        long total = PageInfo.of(goodsList).getTotal();
        Map<String, Object> data = new HashMap<>(2);
        data.put("total", total);
        data.put("items", goodsList);
        return ResponseUtil.ok(data);
    }

    public List<LitemallProduct> operateNum(List<LitemallProduct> products){
        for(int i=0;i<products.size();i++){
            LitemallProduct product=products.get(i);
            if(product.getSmallNumber()==null){
                product.setSmallNumber(0);
            }
            if(product.getNumber()==null){
                product.setNumber(0);
            }
        }
        return products;
    }


    @GetMapping("/warningNum")
    public Object num(){
        List<LitemallProduct> product = productService.queryByNum();
        List<LitemallProduct> products = operateNum(product);
        //计算不足的数量
        int lowTotal = products.stream().filter(m->m.getNumber()<=m.getSmallNumber()).map(LitemallProduct::getGoodsId).collect(Collectors.toSet()).size();
        // 过滤最大数量是null值
        List<LitemallProduct> bigNumIsNotNull = product.stream().filter(m->m.getBigNumber()!=null).collect(Collectors.toList());
        // 计算积压的数量
        int highTotal = bigNumIsNotNull.stream().filter(s->s.getNumber()>=s.getBigNumber()).map(LitemallProduct::getGoodsId).collect(Collectors.toSet()).size();
        Map<String, Object> data = new HashMap<>(16);
        data.put("lowTotal", lowTotal);
        data.put("highTotal",highTotal);
        return ResponseUtil.ok(data);
    }

    @GetMapping("productDetail")
    public Object productDetail(Integer goodId){
        List<LitemallProduct> product = productService.queryByGid(goodId);
        Map<String, Object> data = new HashMap<>(16);
        data.put("product", product);
        return ResponseUtil.ok(data);
    }

    @GetMapping("/totalList")
    public Object totalList(@LoginAdmin Integer adminId,
                       String goodsSn, String name,
                       String sort, String order){
        String[] str = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","AA","BB","CC","DD","EE"};
        List<String> list = Arrays.asList(str);
        List<LitemallGoods> goodsList = goodsService.queryTotalSelective(goodsSn, name, sort, order);
        List<LitemallBrand> brandList = brandService.all();
        List<LitemallCategory> categoryList = categoryService.findAlls();
        List<Object> newList = new ArrayList<>();
        for (LitemallGoods goods:goodsList){
            LitemallGoodsVos litemallGoodsVos = new LitemallGoodsVos();
            BeanUtils.copyProperties(goods,litemallGoodsVos);
            if(goods.getBrandId()!=null && goods.getBrandId()!=0){
                litemallGoodsVos.setBrandName((brandList.stream().filter(a->a.getId().equals(goods.getBrandId()))).findAny().orElse(null).getName());
            }
            if(goods.getCategoryId()!=null && goods.getCategoryId()!=0){
                litemallGoodsVos.setCategoryName((categoryList.stream().filter(a->a.getId().equals(goods.getCategoryId()))).findAny().orElse(null).getName());
            }
            newList.add(litemallGoodsVos);
            Integer goodId = goods.getId();
            List<LitemallProduct> productList = productService.queryByGid2(goodId);
            int i = -1;
            for(LitemallProduct litemallProduct : productList){
                i++;
                LitemallProductVo litemallProductVo =new LitemallProductVo();
                litemallProductVo.setOrderId(goods.getId().toString()+list.get(i));
                litemallProductVo.setIds(litemallProduct.getId());
                litemallProductVo.setIntegral(litemallProduct.getIntegral());
                litemallProductVo.setIntegralFlag(litemallProduct.getIntegralFlag());
                litemallProductVo.setNumber(litemallProduct.getNumber());
                litemallProductVo.setPrice(litemallProduct.getPrice());
                litemallProductVo.setPriceFlag(litemallProduct.getPriceFlag());
                litemallProductVo.setSpecifications(litemallProduct.getSpecifications());
                litemallProductVo.setWeight(litemallProduct.getWeight());
                newList.add(litemallProductVo);
            }
        }
        Map<String, Object> data = new HashMap<>(2);
        data.put("items", newList);

        return ResponseUtil.ok(data);
    }

    /**
     * TODO
     * 目前商品修改的逻辑是
     * 1. 更新litemall_goods表
     * 2. 逻辑删除litemall_goods_specification、litemall_goods_attribute、litemall_product
     * 3. 添加litemall_goods_specification、litemall_goods_attribute、litemall_product
     *
     * 这里商品三个表的数据采用删除再跟新的策略是因为
     * 商品编辑页面，管理员可以添加删除商品规格、添加删除商品属性，因此这里仅仅更新表是不可能的，
     * 因此这里只能删除所有旧的数据，然后添加新的数据
     */
    @PostMapping("/update")
    public Object update(@LoginAdmin Integer adminId, @RequestBody GoodsAllinone goodsAllinone){
        if(adminId == null){
            return ResponseUtil.unlogin();
        }

        LitemallGoods goods = goodsAllinone.getGoods();
        LitemallGoodsAttribute[] attributes = goodsAllinone.getAttributes();
        LitemallGoodsSpecification[] specifications = goodsAllinone.getSpecifications();
        LitemallProduct[] products = goodsAllinone.getProducts();

        if (goods.getIntegralFlag() == null){
            goods.setIntegralFlag(new Byte("1"));
        }
        if (goods.getPriceFlag() == null){
            goods.setPriceFlag(new Byte("1"));
        }
        // 开启事务管理
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus status = txManager.getTransaction(def);
        try {

            // 商品基本信息表litemall_goods
            goodsService.updateById(goods);

            Integer gid = goods.getId();
            specificationService.deleteByGid(gid);
            attributeService.deleteByGid(gid);
            productService.deleteByGid(gid);

            // 商品规格表litemall_goods_specification
            Map<String, Integer> specIds = new HashMap<>(16);
            for(LitemallGoodsSpecification specification : specifications){
                specification.setGoodsId(goods.getId());
                specification.setAddTime(LocalDateTime.now());
                specificationService.add(specification);
                specIds.put(specification.getValue(), specification.getId());
            }

            // 商品参数表litemall_goods_attribute
            for(LitemallGoodsAttribute attribute : attributes){
                attribute.setGoodsId(goods.getId());
                attribute.setAddTime(LocalDateTime.now());
                attributeService.add(attribute);
            }

            // 商品货品表litemall_product
            for(LitemallProduct product : products){
                product.setGoodsId(goods.getId());
                product.setAddTime(LocalDateTime.now());
                product.setIntegralFlag(goods.getIntegralFlag());
                product.setPriceFlag(goods.getPriceFlag());
                productService.add(product);
            }
        } catch (Exception ex) {
            txManager.rollback(status);
            logger.error("系统内部错误", ex);
        }
        txManager.commit(status);

        return ResponseUtil.ok();
    }

    @PostMapping("/delete")
    public Object delete(@LoginAdmin Integer adminId, @RequestBody LitemallGoods goods){
        if(adminId == null){
            return ResponseUtil.unlogin();
        }

        // 开启事务管理
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus status = txManager.getTransaction(def);
        try {

            Integer gid = goods.getId();
            goodsService.deleteById(gid);
            specificationService.deleteByGid(gid);
            attributeService.deleteByGid(gid);
            productService.deleteByGid(gid);
        } catch (Exception ex) {
            txManager.rollback(status);
            logger.error("系统内部错误", ex);
        }
        txManager.commit(status);
        return ResponseUtil.ok();
    }

    @PostMapping("/create")
    public Object create(@LoginAdmin Integer adminId, @RequestBody GoodsAllinone goodsAllinone){
        if(adminId == null){
            return ResponseUtil.unlogin();
        }

        LitemallGoods goods = goodsAllinone.getGoods();
        LitemallGoodsAttribute[] attributes = goodsAllinone.getAttributes();
        LitemallGoodsSpecification[] specifications = goodsAllinone.getSpecifications();
        LitemallProduct[] products = goodsAllinone.getProducts();
        if (goods.getIntegralFlag() == null || "".equals(goods.getIntegralFlag())){
            goods.setIntegralFlag(new Byte("1"));
        }
        if (goods.getPriceFlag() == null || "".equals(goods.getPriceFlag())){
            goods.setPriceFlag(new Byte("1"));
        }
        String name = goods.getName();
        if(goodsService.checkExistByName(name)){
            return ResponseUtil.fail(403, "商品名已经存在");
        }

        // 开启事务管理
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus status = txManager.getTransaction(def);
        try {

            // 商品基本信息表litemall_goods
            goods.setAddTime(LocalDateTime.now());
            goodsService.add(goods);

            // 商品规格表litemall_goods_specification
            Map<String, Integer> specIds = new HashMap<>(16);
            for(LitemallGoodsSpecification specification : specifications){
                specification.setGoodsId(goods.getId());
                specification.setAddTime(LocalDateTime.now());
                specificationService.add(specification);
                specIds.put(specification.getValue(), specification.getId());
            }

            // 商品参数表litemall_goods_attribute
            for(LitemallGoodsAttribute attribute : attributes){
                attribute.setGoodsId(goods.getId());
                attribute.setAddTime(LocalDateTime.now());
                attributeService.add(attribute);
            }

            // 商品货品表litemall_product
            for(LitemallProduct product : products){
                product.setGoodsId(goods.getId());
                product.setAddTime(LocalDateTime.now());
                product.setIntegralFlag(goods.getIntegralFlag());
                product.setPriceFlag(goods.getPriceFlag());
                productService.add(product);
            }
        } catch (Exception ex) {
            txManager.rollback(status);
            logger.error("系统内部错误", ex);
        }
        txManager.commit(status);

        return ResponseUtil.ok();
    }

    @GetMapping("/catAndBrand")
    public Object list2(@LoginAdmin Integer adminId) {
        if (adminId == null) {
            return ResponseUtil.unlogin();
        }

        // http://element-cn.eleme.io/#/zh-CN/component/cascader
        // 管理员设置“所属分类”
        List<LitemallCategory> l1CatList = categoryService.queryL1();
        List<CatVo> categoryList = new ArrayList<>(l1CatList.size());

        for(LitemallCategory l1 : l1CatList){
            CatVo l1CatVo = new CatVo();
            l1CatVo.setValue(l1.getId());
            l1CatVo.setLabel(l1.getName());

            List<LitemallCategory> l2CatList = categoryService.queryByPid(l1.getId());
            List<CatVo> children = new ArrayList<>(l2CatList.size());
            for(LitemallCategory l2 : l2CatList) {
                CatVo l2CatVo = new CatVo();
                l2CatVo.setValue(l2.getId());
                l2CatVo.setLabel(l2.getName());
                children.add(l2CatVo);
            }
            l1CatVo.setChildren(children);

            categoryList.add(l1CatVo);
        }

        // http://element-cn.eleme.io/#/zh-CN/component/select
        // 管理员设置“所属品牌商”
        List<LitemallBrand> list = brandService.alls();
        List<Map<String, Object>> brandList = new ArrayList<>(l1CatList.size());
        for(LitemallBrand brand : list){
            Map<String, Object> b = new HashMap<>(2);
            b.put("value", brand.getId());
            b.put("label", brand.getName());
            brandList.add(b);
        }

        Map<String, Object> data = new HashMap<>(3);
        data.put("categoryList" ,categoryList);
        data.put("brandList", brandList);
        data.put("cateGoryId", SystemConfig.getCateGory());
        return ResponseUtil.ok(data);
    }

    @GetMapping("/newBrand")
    public Object getNewBrand(@LoginAdmin Integer adminId){
        if (adminId == null) {
            return ResponseUtil.unlogin();
        }
        List<LitemallBrandNew> list = newBrandService.alls();
        List<Map<String, Object>> brandList = new ArrayList<>(list.size());
        for(LitemallBrandNew brand : list){
            Map<String, Object> b = new HashMap<>(2);
            b.put("value", brand.getId());
            b.put("label", brand.getName());
            brandList.add(b);
        }
        return ResponseUtil.ok(brandList);
    }

    @GetMapping("/detail")
    public Object detail(@LoginAdmin Integer adminId, Integer id) {
        if (adminId == null) {
            return ResponseUtil.unlogin();
        }

        if (id == null) {
            return ResponseUtil.badArgument();
        }

        LitemallGoods goods = goodsService.findEditById(id);
        List<LitemallProduct> products = productService.queryByGid(id);
        List<LitemallGoodsSpecification> specifications = specificationService.queryByGid(id);
        List<LitemallGoodsAttribute> attributes = attributeService.queryByGid(id);


        Integer categoryId = goods.getCategoryId();
        LitemallCategory category = categoryService.findById(categoryId);
        Integer[] categoryIds = new Integer[]{};
        if (category != null) {
            Integer parentCategoryId = category.getPid();
            categoryIds = new Integer[] {parentCategoryId, categoryId};
        }
        LitemallCategory category1 = categoryService.findById(SystemConfig.getInteger());
        LitemallCategory category2 = categoryService.findById(SystemConfig.getCatePrice());
        Map<String, Object> data = new HashMap<>(10);
        data.put("goods" ,goods);
        data.put("specifications", specifications);
        data.put("products", products);
        data.put("attributes", attributes);
        data.put("categoryIds", categoryIds);
        data.put("piLiangId", SystemConfig.getCateGory());
        data.put("integralId", SystemConfig.getInteger());
        data.put("priceId", SystemConfig.getCatePrice());
        data.put("iName",category1.getName());
        data.put("pName",category2.getName());
        return ResponseUtil.ok(data);
    }

}
